package com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.controller;

import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.LocationEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.LocationQdEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.model.LocationTreeBean;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.model.LocationViewModel;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.LocationEntityService;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.WarehouseEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.MyTokenService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.WarehouseService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 货位部分
 * 仓库管理：订阅仓库数据
 */
@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/location",DxqConfig.pre_pcUrl+"/location"})
public class LocationController {
    private static final Logger logger = LoggerFactory.getLogger(LocationController.class);

    @Autowired
    LocationEntityService locationEntityService;
    @Autowired
    WarehouseService warehouseService;
    @Autowired
    private BaseService baseService;

    @Autowired
    private MyTokenService myTokenService;

    @RequestMapping("/getlocationList")
    public DataResult getlocationList(HttpServletRequest request, String warehouseId, Integer level, String locationCode) {
        DataResult result = new DataResult(1, "操作成功");
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        try {
            List<LocationQdEntity> dataList = locationEntityService.getLocationQdEntityAll(tenantId, warehouseId, level == null ? null : level.toString(), locationCode);
            result.setDataListEx(dataList);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            return result;
        }
    }

    /**
     * 根据货位EPC查询货位信息
     *
     * @param rfidCode
     * @param request
     * @return
     */
    @RequestMapping("/getRfidInfoByCode")
    public DataResult getRfidInfoByCode(String rfidCode, HttpServletRequest request) throws IOException {
        DataResult result = new DataResult(0, "参数异常");
        String tenantId = baseService.getTenantId(request);
        Map<String, Object> reqParams = RequestTool.getParams(request);
        List<String> orgList = baseService.getOrgList(reqParams, "", tenantId);
        if (orgList == null || orgList.size() == 0) {
            result.setMessage("组织权限异常");
            return result;
        }
        List<WarehouseEntity> warehouseList = warehouseService.SelectByOrgIds(orgList, tenantId);
        List<String> strList = warehouseList.stream().map(it -> it.getId().toString()).collect(Collectors.toList());
        result = locationEntityService.selectLocationByEpc(rfidCode, tenantId, strList);
        return result;
    }

    /**
     * 用于手持设备货位仓库列表
     */
    @RequestMapping("/getWarehouseList")
    public DataResult<WarehouseEntity> getWarehouseList(HttpServletRequest request, @RequestParam(defaultValue = "",
            required = false) String access_token) {
        DataResult<WarehouseEntity> result = new DataResult<>();
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        try {
            List<WarehouseEntity> list = warehouseService.SelectAll(tenantId);
            List<String> orgList = baseService.getOrgListByUserId(userId, tenantId);
            list = list.stream().filter(it -> orgList.contains(it.getOrg()) && it.getiUsed().equals("enable")).collect(Collectors.toList());
            result.setDataList(list);
            result.setStatus(1);
            result.setMessage("操作成功");
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 根据货位ID获取子数据列表
     *
     * @param locationID
     * @param level
     * @param request
     * @return
     */
    @RequestMapping("/GetList")
    public DataResult GetList(String locationID, String level, String locationCode, HttpServletRequest request) {
        DataResult dataResult = new DataResult(1, "查询成功");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, Object> myParams = RequestTool.getParams(request);
            List<LocationViewModel> dataList = new ArrayList<>();
            dataList = locationEntityService.GetList(locationID, level, tenantId, locationCode);
            dataResult.setDataList(dataList);
        } catch (Exception ex) {
            dataResult.setStatus(0);
            dataResult.setMessage(ex.getMessage());
        }
        return dataResult;
    }

    /**
     * 货位树结构查询
     *
     * @return
     */
    @RequestMapping("/GetLocationTree")
    public DataResult<LocationTreeBean> GetLocationTree(@RequestParam(defaultValue = "", required = false) String locationId,
                                                        @RequestParam(defaultValue = "", required = false) String orgid,
                                                        HttpServletRequest request) throws IOException {
        DataResult dataResult = new DataResult<LocationTreeBean>();
        dataResult.setStatus(1);
        dataResult.setMessage("查询成功");
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);

        Map<String, Object> reqParams = RequestTool.getParams(request);
        String strOrgids = (String) reqParams.get("orgids");
        List<String> strList = new ArrayList<>();
        if (!orgid.equals("null") && !StringUtils.isEmpty(orgid)) strList.add(orgid);
        else {
            if (!StringUtils.isEmpty(strOrgids)) {
                strList.addAll(new ArrayList<>(Arrays.asList(strOrgids.split(","))));
            } else {
                List<String> myList = baseService.getOrgListByUserId(userId, tenantId);
                strList.addAll(myList);
            }
        }
        List<LocationTreeBean> rList = locationEntityService.GetLocationTree(locationId, strList, tenantId);
        dataResult.setDataList(rList);
        dataResult.setTotalSizeEx(rList.size());
        return dataResult;
    }

    /**
     * 检索子级数量
     *
     * @param locationId
     * @return
     */
    @RequestMapping("/GetLocationNumByParentId")
    public DataResult GetLocationNumByParentId(String locationId, HttpServletRequest request) {
        DataResult res = new DataResult(1, "查询成功");
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);

        int rInt = locationEntityService.GetLocationNumByParentId(locationId, tenantId);
        res.setData(rInt);
        return res;
    }

    @RequestMapping("/GetLocationNumByParentIds")
    public DataResult GetLocationNumByParentIds(String locationIds, HttpServletRequest request) {
        DataResult res = new DataResult(1, "查询成功");
        res.setData(0);
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        if (StringUtils.isEmpty(locationIds)) return res;
        List<String> ids = Arrays.asList(locationIds.split(","));
        List<LocationEntity> list_Entity = locationEntityService.getLocationByWhIds(ids, tenantId);
        List<String> mesList = new ArrayList<>();
        for (String key : ids) {
            List<LocationEntity> tempList = list_Entity.stream().filter(it -> !it.getId().equals(key)).collect(Collectors.toList());
            if (tempList.size() > 0)
                mesList.add(String.format("%s[%s],有子数据不允许操作", tempList.get(0).getWarehouse_name(), tempList.get(0).getId()));
        }
        if (mesList.size() > 0) {
            res.setData(1);
            res.setMessage(String.join(";", mesList));
        }

        return res;
    }

    /**
     * 是否可以删除 true 可以 false 不可以
     *
     * @param locationId
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/CheckLocationDel")
    public DataResult CheckLocationDel(String locationId, HttpServletRequest request) throws Exception {
        DataResult res = new DataResult(1, "查询成功");
        try {
            res.setData(false);
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);

            int rInt = locationEntityService.GetLocationNumByParentId(locationId, tenantId);
            if (rInt > 0) return res;
            int checkNum = locationEntityService.GetEPCNumByLocationId(locationId, tenantId);
            if (rInt == 0 && checkNum == 0) res.setData(true);
        } catch (Exception ex) {
            logger.error("[CheckLocationDel]" + ex.getMessage());
        }
        return res;
    }

    @RequestMapping("/EditWarehouseById")
    public DataResult EditWarehouseById(String id, String isEnabled, String tenant_id) {
        DataResult res = new DataResult(0, "操作失败");
        try {
            logger.info("[EditWarehouseById]" + id + "|" + isEnabled + "|" + tenant_id);
            WarehouseEntity warehouseEntity = warehouseService.SelectById(Long.valueOf(id), tenant_id);
            if (warehouseEntity != null) {
                if (isEnabled.equals("true") || isEnabled.equals("1")) {
                    warehouseEntity.setiUsed("enable");
                    warehouseEntity.setIsEnabled("true");
                } else {
                    warehouseEntity.setiUsed("disable");
                    warehouseEntity.setIsEnabled("false");
                }
                int rInt = warehouseService.UpdateEntity(warehouseEntity);
                if (rInt > 0) {
                    res = new DataResult(1, "操作成功");
                }
            }
        } catch (Exception ex) {
            logger.error("[EditWarehouseById]" + ex.getMessage());
        }
        return res;
    }

    @RequestMapping("/EditLocationEnd")
    public DataResult EditLocationEnd(HttpServletRequest request, String id, int isEnd){
        String tenantId = baseService.getTenantId(request);
        DataResult res = new DataResult(0, "操作失败");
        int rInt = locationEntityService.UpdateLocationForEnd(tenantId, id, isEnd);

        if (rInt > 0) {
            res = new DataResult(1, "操作成功");
            res.setData(rInt);
        }
        return res;
    }

    /**
     * 删除后检测
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/CheckLocationEnd")
    public DataResult EditLocationEnd(HttpServletRequest request, String id){
        String tenantId = baseService.getTenantId(request);
        DataResult res = new DataResult(0, "操作失败");
        int rInt = locationEntityService.UpdateLocationForEnd(tenantId, id);

        if (rInt > 0) {
            res = new DataResult(1, "操作成功");
            res.setData(rInt);
        }
        return res;
    }

}
